import axios from 'axios'
import Vue from 'vue'
import router from '@/router/index'

import '@/common/plugins/element.js'
// 创建axios实例
const _this = this

const service=axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 10000, // 请求超时时间
  headers:{
    'Content-type': 'application/json',
  }
})

//异步请求前在header里加入token
service.interceptors.request.use(
  config => {
    if(config.url =='/login'){
      //如果是登录和注册操作，则不需要携带header里面的token
    }else{
      var isLogin = localStorage.getItem("utoken")  ?  localStorage.getItem("utoken") : false
      if (isLogin) {
        config.headers.authorization = localStorage.getItem('utoken');
      }else{
        router.push({
          path:"/login"
        }).catch(err => {err})
      }
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  });

// 响应拦截器
service.interceptors.response.use(
  response => {
    if(response.data.status != "200"){
      // Vue.prototype.$notify.error({
      //     title: '错误',
      //     message: response.data.msg
      //   });
    }else if(response.data.status === "500"){
      router.push({
        path:"/login"
      }).catch(err => {err})
    }
    return response
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          breeak
        case 401:
          error.message = '未授权，请登录'
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器内部错误'
          break
        case 501:
          error.message = '服务未实现'
          break
        case 502:
          error.message = '网关错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
          break
      }
    } else {
       error.message = '服务器连接失败'
    }
    Vue.prototype.$notify.error({
        title: '错误',
        message: error.message
      });
    return Promise.reject(error)
  }
)

export default service
